#include "packetbase.h"

PacketBase::PacketBase() {
    head[0] = 0xAC;
    head[1] = 0xBC;

    checksum = 0x00;
}

QString PacketBase::decode(QByteArray rawData)
{
    int offset = 0;

    if (rawData != nullptr) {
        if (rawData.size() != PACKET_LENGTH) {
            return "";
        }

        memcpy(this->rawData, rawData.constData(), PACKET_LENGTH);
    }

    memcpy(head, this->rawData + offset, sizeof(head));

    offset += HEAD_LENGTH;
    memcpy(&id, this->rawData + offset, sizeof(id));

    offset += ID_LENGTH;
    memcpy(&longitude, this->rawData + offset, sizeof(longitude));

    offset += LONGITUE_LENGTH;
    memcpy(&latitude, this->rawData + offset, sizeof(latitude));

    offset += LATITUDE_LENGTH;
    memcpy(&depth, this->rawData + offset, sizeof(depth));

    offset += DEPTH_LENGTH;
    memcpy(&temperature, this->rawData + offset, sizeof(temperature));

    offset += TEMPERATURE_LENGTH;
    memcpy(&checksum, this->rawData + offset, sizeof(checksum));

    return toHexString();
}

QString PacketBase::encode()
{
    int offset = 0;
    memcpy(rawData + offset, head, sizeof(head));

    offset += HEAD_LENGTH;
    memcpy(rawData + offset, &id, sizeof(id));

    offset += ID_LENGTH;
    memcpy(rawData + offset, &longitude, sizeof(longitude));

    offset += LONGITUE_LENGTH;
    memcpy(rawData + offset, &latitude, sizeof(latitude));

    offset += LATITUDE_LENGTH;
    memcpy(rawData + offset, &depth, sizeof(depth));

    offset += DEPTH_LENGTH;
    memcpy(rawData + offset, &temperature, sizeof(temperature));

    offset += TEMPERATURE_LENGTH;
    memcpy(rawData + offset, &checksum, sizeof(checksum));


    return toHexString();
}

void PacketBase::setCoordinate(unsigned int longitude, unsigned int latitude)
{
    if (isValidCoord(longitude, latitude)) {
        this->longitude = longitude;
        this->latitude = latitude;
    }
}

void PacketBase::setDepth(SHORT depth)
{
    if (isValidDepth(depth)) {
        this->depth = depth;
    }
}

void PacketBase::resetData()
{
    memset(rawData, 0, PACKET_LENGTH);

    this->id = 0;
    this->longitude = 0;
    this->latitude = 0;
    this->depth = 0;
    this->temperature = 0;

}

bool PacketBase::isValidCoord(unsigned int longitude, unsigned int latitude)
{
    if (longitude < PacketBase::LONGITUE_MIN || longitude > PacketBase::LONGITUE_MAX) {
        return false;
    }

    if (latitude < PacketBase::LATITUDE_MIN || latitude > PacketBase::LATITUDE_MAX) {
        return false;
    }

    return true;
}

bool PacketBase::isValidDepth(unsigned short depth)
{
    if (depth >= 0 && depth <= PacketBase::DEPTH_MAX) {
        return true;
    }

    return false;
}

QString PacketBase::toHexString()
{
    QString str;
    for (int i = 0; i < PACKET_LENGTH; ++i) {
        // 将每个 unsigned char 转换为两位十六进制字符串
        str.append(QString("%1").arg(rawData[i], 2, 16, QChar('0')).toUpper());
    }

    return str;
}
